using System;
using System.Collections.Generic;
using System.Text;

namespace Tycho.Parser.Peg {
    class InterpolatedStringBuilder {
        private int StartIndex;
        private int StringStartIndex;
        private readonly Func<int, int, SourceInformation> CreateSourceInformation;
        private StringBuilder StringBuilder;
        private List<ITerm> Terms;
        private int EndIndex;

        public InterpolatedStringBuilder (int startIndex, Func<int, int, SourceInformation> createSourceInformation) {
            StartIndex = startIndex;
            StringStartIndex = startIndex;
            CreateSourceInformation = createSourceInformation;
            StringBuilder = new StringBuilder();
            Terms = null;
        }

        public void AddString (string s, int endIndex) {
            StringBuilder.Append (s);
            EndIndex = endIndex;
        }

        public ITerm CreateTerm (int endIndex) {
            if (Terms != null) {
                AddRemainingString ();

                var resultTerm = new CompositeTerm ("interpolated-string", CreateSourceInformation (StartIndex, endIndex - StartIndex));

                foreach (var term in Terms) {
                    resultTerm.Add ("components", term, true);
                }

                return resultTerm;
            } else {
                return new StringTerm (StringBuilder.ToString (), CreateSourceInformation (StringStartIndex, endIndex - StringStartIndex));
            }
        }

        private void AddRemainingString () {
            if (StringBuilder.Length > 0) {
                Terms.Add (new StringTerm (StringBuilder.ToString (), CreateSourceInformation (StringStartIndex, EndIndex - StringStartIndex)));
                StringBuilder = new StringBuilder ();
            }
        }

        public void AddTerm (ITerm term2, int endIndex) {
            if (Terms == null) {
                Terms = new List<ITerm> ();
            }

            AddRemainingString ();
            Terms.Add (term2);

            EndIndex = endIndex;
            StringStartIndex = endIndex;
        }
    }
}